<?	require_once '_lib/_ziplib.php';

if (!permitted('edit', $node = (int)param('node'))) {
	header("Location: "._transformURL($CURRENT->url, array('remove_params' => 'all', 'add_param' => "node:$node")));
	exit;
}

$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
$ws = $xhr ? '' : '<textarea>';
$we = $xhr ? '' : '</textarea>';

$DATA['components'] = array();

if (($temp = @glob($_SERVER['DOCUMENT_ROOT'].FP_COMPONENT_PATH.'*', GLOB_ONLYDIR)) && sizeof($temp)) {
	foreach ($temp as $t)
		$DATA['components'][] = substr(strrchr($t, "/"), 1);
}

if (($c = (int)param('import')) && ($temp = datafetch('db_item', tb('data'), "id_data=".D_MULTIBLOCK." AND id_parent in (".$DATA['page']['id'].", 0) AND id=$c")) && in_array($temp['value'], $DATA['components'])) {
	
	$DATA['component'] = array_merge($temp, array('path' => $_SERVER['DOCUMENT_ROOT'].FP_COMPONENT_PATH.$temp['value']));
	
	$_plugin = $temp['value'];

	if (is_file("_template/{$CONTEXT[template]}/lang-{$CONTEXT[lang]}.php")) {		// template localization
		include "_template/{$CONTEXT[template]}/lang-{$CONTEXT[lang]}.php";
	}
	
	if (file_exists("{$DATA[component][path]}/admin/import/init.php")) {

		set_time_limit(300);

		ob_start();


		if (($f = $_FILES['import']) && $f['tmp_name'][$c]) {
			
			if ($zip = @zip_open($f['tmp_name'][$c])) {

				if ((@zip_entry_name($d = @zip_read($zip)) == 'data.xml') && (@zip_entry_open($zip, $d, "r"))) {
					
					if (($e['xml'] = DOMDocument::loadXML(@zip_entry_read($d, @zip_entry_filesize($d)))) && 
						($e['root'] = $e['xml']->getElementsByTagName('sbse')) && $e['root']->length && ($e['root'] = $e['root']->item(0))) {
						
						if ($e['root']->getAttribute('type') == $_plugin) {



							diags( include "{$DATA[component][path]}/admin/import/init.php" );


	
						} else diags('<p class="error">'.t('This data relies to another component type', 'tpl').'</p>');
	
					} else diags('<p class="error">'.t('Component data is broken', 'tpl').'</p>');
	
				} else diags('<p class="error">'.t('Wrong archive', 'tpl').'</p>');
			
				@zip_close($zip);
				
			} else diags('<p class="error">'.t("Can't open file", 'tpl').'</p>');

		} else diags('<p class="error">'.t('Please choose the data file to upload', 'tpl').'</p>');


		header("Content-Type: text/html; charset=utf-8");
		?><?=$ws.php2js(array('diags' => implode('', $GLOBALS['DIAGS']), 'debug' => ob_get_clean())).$we?><?
		exit;
	}

} else {	// **** no such component ****

	header("Content-Type: text/html; charset=utf-8");
	?><?=$ws.php2js(array('diags' => '<p class="error">'.t('No such component', 'tpl').'</p>', 'debug' => ob_get_clean())).$we?><?
	exit;
}